package com.applet.orderdetail.service.impl;

import com.applet.entity.OrderDetail;
import com.applet.entity.ShoppingCart;
import com.applet.orderdetail.mapper.OrderDetailMapper;
import com.applet.orderdetail.service.OrderDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 订单详细 serviceImpl
 */
@Slf4j
@Service
public class OrderDetailServiceImpl implements OrderDetailService {


    @Resource
    private OrderDetailMapper orderDetailMapper;



    /**
     * 订单明细
     *        新增订单详细数据
     * @param shoppingCartList
     * @param orderId
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void addOrderDetailList(List<ShoppingCart> shoppingCartList, Long orderId) {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        if( !CollectionUtils.isEmpty(shoppingCartList) ){
            for (ShoppingCart shoppingCart : shoppingCartList) {
                OrderDetail orderDetail = OrderDetail.init(shoppingCart.getName(), shoppingCart.getImage(), orderId, shoppingCart.getDishId(), shoppingCart.getSetmealId(), shoppingCart.getDishFlavor(), shoppingCart.getNumber(), shoppingCart.getAmount());
                Integer count = orderDetailMapper.insert(orderDetail);
                atomicInteger.incrementAndGet();
            }
        }
        log.info("订单id: {},新增: {}条详细数据", orderId, atomicInteger.get());
    }



    /**
     * 订单明细
     *        根据订单id查询明细列表
     * @param orderId
     */
    @Override
    public List<OrderDetail> selectOrderDetailListByOrderId(Long orderId) {
        return orderDetailMapper.selectOrderDetailListByOrderId(orderId);
    }


}
